export default {
	methods: {
		parseRes(res,dataField) {
			if(!dataField){
				dataField=this.dataField;
			}
			var data = [];
			if (dataField) {
				var datas = dataField.split(".");
				var data = res;
				for (var i = 0; i < datas.length; i++) {
					data = data[datas[i]]
				}
			} else {
				data = res;
			}
			return data;
		},
		parseData(data,idField,textField,parentField) {
			if(!idField){
				idField=this.idField;
			}
			if(!textField){
				textField=this.textField;
			}
			if(!parentField){
				parentField=this.parentField;
			}
			var tmp = this.deepClone(data);
			var source = this.listToTree(tmp, idField, parentField);
			this.genTreeData(source, textField, idField)
			return source;
		},
		genTreeData(ary, name, value) {
			ary.forEach((item) => {
				var row = {
					label: item[name],
					value: item[value]
				};
				Object.assign(item, row);
				if (item.children && item.children.length > 0) {
					this.genTreeData(item.children, name, value);
				}
			});
		},
		deepClone(source) {
			if (!source && typeof source !== "object") {
				throw new Error("error arguments", "deepClone");
			}
			const targetObj = source.length>=0 ? [] : {};
			Object.keys(source).forEach((keys) => {
				if (source[keys] && typeof source[keys] === "object") {
					targetObj[keys] = this.deepClone(source[keys]);
				} else {
			  targetObj[keys] = source[keys];
				}
			});
			return targetObj;
		},
		listToTree(ary, idKey, pidKey) {
			var obj = {};
			//先对数据进行整理 map[key]=obj;
			for (var i = 0; i < ary.length; i++) {
				var o = ary[i];
				if (this.async) {
					ary[i].children = [];
				}
				obj[o[idKey]] = ary[i];
			}
			var rtnAry = [];
			for (var i = 0; i < ary.length; i++) {
				var json = ary[i];
				var id = json[idKey];
				var pid = json[pidKey];
				if (obj[pid] && id != pid) {
					var parent = obj[pid];
					parent.children = parent.children || [];
					parent.children.push(json);
				} else {
					rtnAry.push(json);
				}
			}
			return rtnAry;
		}
	}
}
